package com.sakura.takeaway.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sakura.takeaway.common.CustomException;
import com.sakura.takeaway.entity.Category;
import com.sakura.takeaway.entity.Dish;
import com.sakura.takeaway.entity.Setmeal;
import com.sakura.takeaway.mapper.CategoryMapper;
import com.sakura.takeaway.service.CategoryService;
import com.sakura.takeaway.service.DishService;
import com.sakura.takeaway.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author Sakura
 * @Date 2022-07-10 13:53
 */
@Service
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private DishService dishService;
    @Autowired
    private SetmealService setmealService;

    /**
     * 根据id删除分类，删除之前需要判断是否关联了菜品（dish)、套餐（setmeal）
     * @param id
     */
    @Override
    public void remove(Long id) {

        //菜品查询
        LambdaQueryWrapper<Dish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据id进行分类查询
        dishLambdaQueryWrapper.eq(Dish::getCategoryId, id);
        int countDish = dishService.count(dishLambdaQueryWrapper);

        //查询当前分类是否关联菜品(dish)，如果已经关联，抛出一个业务异常
        if(countDish > 0){
            //如果已经关联，抛出一个业务异常
            throw new CustomException("当前分类关联了菜品，不能删除");

        }

        //套餐查询
        LambdaQueryWrapper<Setmeal> setmealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //添加查询条件，根据id进行分类查询
        setmealLambdaQueryWrapper.eq(Setmeal::getCategoryId,id);
        int countSetmeal = setmealService.count(setmealLambdaQueryWrapper);

        //查询当前分类是否关联套餐(setmeal)，如果已经关联，抛出一个业务异常
        if(countSetmeal > 0){
            //如果已经关联，抛出一个业务异常
            throw new CustomException("当前分类关联了套餐，不能删除");
        }

        //正常删除
        super.removeById(id);

    }
}
